<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{




    /**
     * 首页
     */
    public function index()
    {
        $id = session('user.id');
        $user = session('user');
        $weixin_id = session('weixin_user.id');
        if(empty($weixin_id)){
            $this->wechatLogin();
        }

        if(empty($id)){
            return $this->login();
        }else{
            $data = Db('news')->where('news_statuid',1)->order('id desc')->limit(0,3)->select();
            $banner = Db('banner')->where('status',1)->select();
            $this->assign('data',$data);
            $this->assign('banner',$banner);
            // $this->assign('signPackage',$this->getSignPackage());//分享
            return $this->fetch();
        }
    }


    /**
     * ajax获取新闻数据
     */
    public function ajaxnewsdata(){
        $num = input('param.num');
        $count = Db('news')->where('news_statuid',1)->count();
        //判断接受的数值是否大于总数据数
        if($num<$count){
            $data['news'] = Db('news')->where('news_statuid',1)->order('id desc')->limit($num,3)->select();
            $data['num'] = $num;
            $data['code'] = 1;
            $data['count'] = $count;
            return $data;
        }else{
            $data['code'] = 0;
            return $data;
        }

    }


    /**
     * ajax获取banner
     */
    public function ajaxbanner(){
        $banner['banner'] = Db('banner')->where('status',1)->select();
        $banner['code']=1;
        return $banner;
    }


    /**
     * 登录页面
     */
    public function login(){

        return view('index/login');
    }

    /**
     * 登录验证
     */
    public function do_login(){
        if(request()->isPost()){
            $post = input('post.');
            $email = $post['email'];
            if(empty($email)){
                return ['code'=>400,'message'=>'邮箱不能为空'];
            }
            $password = $post['password'];
            if(empty($password)){
                return ['code'=>400,'message'=>'密码不能为空'];
            }
            $data['password'] = Db('user')->where('email',$email)->value('password');
            if($data['password']){
                if(md5($password) == $data['password']){
                    $audit = Db('user')->where('email',$email)->value('audit');
                    if($audit == 1){
                        $user = Db('user')->where('email',$email)->find();
                        session('user',$user);
                        $id = session('user.id');
                        $openid = session('weixin_user.openid');
                        // return $id;
                        $num = Db('user')->where('openid',$openid)->value('openid');
                        if(empty($num)){
                            $data = Db('user')->where('id',$id)->update(['weixin_id'=>session('weixin_user.id'),'openid'=>$openid,'nickname'=>session('weixin_user.nickname'),'headimage'=>session('weixin_user.headimgurl')]);
                            // return $data;
                            if($data>0){
                                return ['code'=>1,'message'=>'登录成功'];
                            }
                        }
                        return ['code'=>1,'message'=>'登录成功'];

                    }else{
                        return ['code'=>400,'message'=>'您的账号正在审核'];
                    }

                }else{
                    return ['code'=>400,'message'=>'密码不正确'];
                }
            }else{
                return ['code'=>400,'message'=>'用户不存在'];
            }

        }
    }


    /**
     * 注册页面
     */
    public function register(){

        $openid = session('weixin_user.openid');
        $num = Db('user')->where('openid',$openid)->value('openid');
        if(!empty($num)){
            return $this->error('该微信号已注册');
        }
        if(request()->isPost()){
            $post = input('param.');
            if((!empty($post['mob']))&&(!empty($post['email']))&&(!empty($post['username']))&&(!empty($post['password']))&&(!empty($post['passwords']))&&(!empty($post['company']))&&(!empty($post['position']))){
                if(!preg_match('/^1[34578]\d{9}$/',$post['mob'])){
                    return ['code'=>400,'message'=>'电话格式不对'];
                }
                if(!preg_match('/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/',$post['email'])){
                    return ['code'=>400,'message'=>'邮箱格式不对'];
                }
                if($post['password'] !== $post['passwords']){
                    return ['code'=>400,'message'=>'两次密码不一致'];
                }
                $return = Db('user')->where('email',$post['email'])->find();
                if(!empty($return)){
                    return ['code'=>400,'message'=>'该邮箱已注册'];
                }
                $email = substr(strstr($post['email'],'@'),1);
                $test = Db('suffix')->where('suffix',$email)->find();
                if(!empty($test)){
                    $audit = 1;
                }else{
                    $audit = 0;
                }
                $data['audit'] =  $audit;
                $data['email'] = $post['email'];
                $data['password'] = md5($post['password']);
                $data['company'] = $post['company'];
                $data['position'] = $post['position'];
                $data['username'] = $post['username'];
                $data['mob'] = $post['mob'];
                $id = Db('user')->insertGetId($data);
                if($id>0){
                    $user = Db('user')->where('id',$id)->find();
                    session('user',$user);
                    $id = session('user.id');
                    $openid = session('weixin_user.openid');
                    // return $openid;
                    $data = Db('user')->where('id',$id)->update(['weixin_id'=>session('weixin_user.id'),'nickname'=>session('weixin_user.nickname'),'openid'=>$openid,'headimage'=>session('weixin_user.headimgurl')]);
                    if($data>0){
                        return ['code'=>1,'message'=>'注册成功'];
                    }

                    return ['code'=>1,'message'=>'注册成功'];
                }else{
                    return ['code'=>400,'message'=>'添加数据库失败'];
                }
            }else{
                return ['code'=>400,'message'=>'表单填写不完整'];
            }
        }

        return view('register');

    }


    /**
     * 个人中心
     */
    public function personcenter(){
       $id = $this->is_login();
        $data = Db('user')->where(['id'=>$id])->find();
        $this->assign('data',$data);
        return $this->fetch();
    }


    /**
     * 确保用户已登录
     */
    public function is_login(){
        $id = session('user.id');
        if(!empty($id)){
            $audit = Db('user')->where('id',$id)->value('audit');
            if($audit !== 1){
                return $this->redirect('index/login');
            }
        }else{
            return $this->redirect('index/login');
        }

        return $id;
    }


    /**
     * 修改
     */
    public function edit(){
        $id = $this->is_login();
        if(request()->isPost()){
            $post = input('param.');
            $key = $post['key'];
            if(empty($post['value'])){
                $data = ['code'=>400,'msg'=>'表单不能为空'];
                return $data;
            }
            if($key == 'mob'){
                if(!preg_match('/^1[34578]\d{9}$/',$post['value'])){
                    return ['code'=>400,'message'=>'电话格式不对'];
                }
            }
            if($key == 'email'){
                if(!preg_match('/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/',$post['value'])){
                        return ['code'=>400,'message'=>'邮箱格式不对'];
                    }
            }
            $return = Db('user')->where(['id'=>$id])->setField($key,$post['value']);
            if($return>0){
                $data = ['code'=>1,'msg'=>'修改成功'];
                return $data;
            }else{
                $data = ['code'=>400,'msg'=>'修改失败'];
                return $data;
            }
        }
    }


    /**
     * 活动页面
     */
    public function events(){
        $this->is_login();
        // $data = Db('activity')->where('statuid',1)->order('id desc')->limit(0,3)->select();
        // $this->assign('data',$data);
        return view('events');
    }


    /**
     * ajax获取活动列表
     */
    public function ajaxevents(){
        $count = Db('activity')->where('statuid',1)->count();
        $num = input('param.num');
        if($num>$count){
            $data['num'] = $num;
            $data['code'] = 0;
            return $data;
        }else{
            $data['events'] = Db('activity')->where('statuid',1)->order('id desc')->limit($num,3)->select();
            $data['code'] = 1;
            $data['num'] = $num;
            return $data;
        }
    }

    /**
     * 活动报名
     */
    public function enroll(){
        $param = input('param.');
        $id = $this->is_login();
        $data = Db('enroll')->where(['uid'=>$id,'eid'=>$param['events_id']])->find();
        if(!empty($data)){
            $data['code'] = 3;
            return $data;
        }
        $num = Db('enroll')->insert(['uid'=>$id,'eid'=>$param['events_id']]);
        if($num>0){
            $data['code'] = 1;
            return $data;
        }else{
            $data['code'] = 0;
            return $data;
        }

    }


    /**
     * loading页面
     */
    public function loading(){
        return $this->fetch();
    }


    /**
     * 退出
     */
    public function login_out(){
        session('user',null);
        $this->login();
    }


    /**
     * 新闻头条
     */
    public function headlines(){
        $data = Db('news')->where(['news_statuid'=>1,'headlines'=>1])->order('id desc')->select();
        $banner = Db('banner')->where('status',1)->select();
        $this->assign('banner',$banner);
        $this->assign('data',$data);
        return $this->fetch();
    }


    /**
    * =========获取微信用户详细信息=====================
    **/
    public function wechatLogin(){
        //-------配置
        $AppID = 'wxa4dbcdb9506a00e2';
        $AppSecret = '838df0c27d021f8fb025c56a06d9d05a';

        // nutrue
        // $AppID = 'wxce3c148000dc10f2';
        // $AppSecret = 'f3352cd85f160e7547e2c378561ad45b';


        $callback  = 'http://www.juplus.cn/vdma/index/index/wechatCllBack';  //url('index/index/wechatCllBack'); //回调地址

         //微信登录
         //-------生成唯一随机串防CSRF攻击
        $state  = md5(uniqid(rand(), TRUE));
        $_SESSION["wx_state"]    =   $state; //存到SESSION snsapi_userinfo snsapi_base
        $callback = urlencode($callback);
        $wxurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$AppID."&redirect_uri=".$callback."&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
        header("Location: $wxurl");

    }
        //微信登录回调函数
    public function wechatCllBack() {
        $AppID = 'wxa4dbcdb9506a00e2';
        $AppSecret = '838df0c27d021f8fb025c56a06d9d05a';

        // nutrue
        // $AppID = 'wxce3c148000dc10f2';
        // $AppSecret = 'f3352cd85f160e7547e2c378561ad45b';


        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppID.'&secret='.$AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json =  curl_exec($ch);
        curl_close($ch);
        $arr=json_decode($json,1);
         //得到 access_token 与 openid

        $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json =  curl_exec($ch);
        curl_close($ch);
        $arr=json_decode($json,1);

        header("content-type:text/html;charset=utf-8");         //设置编码
         //得到 用户资料
        $this->_login_handle($arr);

    }

    /**
     * 获取签名
     *
     */
    function getSignPackage() {
        // $AppID = 'wxb42ad5150aacbee4';
        // $AppSecret = '8b023a4ec3bfb58ecaf1b96b95b2e1ba';
        $AppID = 'wxa4dbcdb9506a00e2';
        $AppSecret = '838df0c27d021f8fb025c56a06d9d05a';

        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $jsapiTicket = $this->getJsApiTicket($AppID,$AppSecret);

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $AppID,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,

        );
        return $signPackage;
    }

    function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    function getJsApiTicket($appid,$appsecret) {
        $accessToken = $this->getAccessToken($appid,$appsecret);
        $access_token = json_decode($accessToken);
        $access_token = $access_token->access_token;

        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$access_token";
        $res = json_decode($this->httpGet($url));
        $ticket = $res->ticket;
        return $ticket;
    }


    function getAccessToken($appid,$appsecret) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $res = json_decode($this->httpGet($url));
        $access_token = $res->access_token;
        return json_encode(array("access_token"=>$access_token));
    }

    function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }


    private function _login_handle($user_info){
        $user_oauth = Db('weixin_user')->where(array("openid"=>$user_info['openid']))->find();
        if(empty($user_oauth)){
            /*二【如果用户不存在】
            * @1添加该用户到users
            */
            $nickname = base64_encode($user_info['nickname']);
            $new_user_data = array(
                'openid' => $user_info['openid'],
                'nickname' => $nickname, //名称
                'sex' => $user_info['sex'],//性别
                'city' => $user_info['city'],//城市
                'province' => $user_info['province'],//省份
                'country' => $user_info['country'], //国家
                'headimgurl' => $user_info['headimgurl'],//头像
                'create_time' => date("Y-m-d H:i:s"),

            );
            // dump($new_user_data);exit;
            $new_user_data['id'] = Db('weixin_user')->insertGetId($new_user_data);
            $weixin_user_data = Db('weixin_user')->where('id',$new_user_data['id'])->find();
            // Db('user')->insert(['weixin_id'=>$new_user_data['id'],'nickname'=> $nickname,'headimgurl'=>$user_info['headimgurl']]);
            $user_oauth = $weixin_user_data;
        }
        // dump($user_oauth);exit;
        session('weixin_user',$user_oauth);
        $uid = session('user.id');
        // dump(session('weixin_user'));exit;
        $this->redirect(url('index'));
    }











}
